package com.tianpengcc.web;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.tianpengcc.model.User;
import com.tianpengcc.service.UserService;
import com.tianpengcc.service.impl.UserServiceImpl;

public class LoginServlet extends HttpServlet {
	
	private UserService userService = new UserServiceImpl() ;
	
	/**
	 * <p>Description:</p>
	 * <p>Compary</p>
	 * @author 田鹏
	 * @date 2017年10月24日下午3:06:04
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * The doGet method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to get.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request,response); 
	}

	/**
	 * The doPost method of the servlet. <br>
	 *
	 * This method is called when a form has its tag value method equals to post.
	 * 
	 * @param request the request send by the client to the server
	 * @param response the response send by the server to the client
	 * @throws ServletException if an error occurred
	 * @throws IOException if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		try {
			String userName = request.getParameter("userName");
			String password = request.getParameter("password");
			User user = new User(userName,password) ;
			
			User resultUser = userService.findByUser(user);
			if(resultUser == null ){
				request.setAttribute("error", "用户名或密码错误！");
				request.setAttribute("user", user);
				request.getRequestDispatcher("/login.jsp").forward(request, response); ;
			}else{
				String remenber = request.getParameter("remember");
				if("remember-me".equals(remenber)){
					Cookie cookie = new Cookie("user",userName + "---" + password);
					cookie.setMaxAge(60 * 60 * 24 * 7);
					response.addCookie(cookie);
				}
				
				HttpSession session = request.getSession();
				session.setAttribute("user", resultUser);
				response.sendRedirect(request.getContextPath() + "/main");
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.sendRedirect(request.getContextPath() + "/error.jsp");
		}
	}

}
